import React, {Component} from 'react';
import {View, StyleSheet, Text, Image, Alert, ActivityIndicator, FlatList, RefreshControl} from 'react-native';
import {Flex, WingBlank, List, Tabs, Modal, Toast} from '@ant-design/react-native';
import {getBankApplyList, setApplyState, setContractState, setBankPayState} from '~/api/bank';
import {connect} from 'react-redux';

const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
        system: state.system,
    };
};
const renderContent = (tab, index) => {
    const style = {
        paddingVertical: 40,
        justifyContent: 'center',
        alignItems: 'center',
        margin: 10,
        backgroundColor: '#ddd',
    };
};
let pagecount = 0;
let index = 1;
let size = 10;
class myLoan extends Component {
    static navigationOptions = {
        title: '我的贷款',
    };
    constructor(props) {
        super(props);
        this.state = {
            list: [],
            index: this.props.navigation.getParam('params'),
            tabinfo: [],
            tabs: [
                {title: '全部贷款', value: '0'},
                {title: '待办贷款', value: '1'},
                {title: '审核通过', value: '2'},
                {title: '放款成功', value: '3'},
                {title: '审核失败', value: '4'},
            ],
            queryCondidate: {
                page_index: 1,
                page_size: 10,
                condidate: {
                    //tabkey: 'all',
                    state: 0,
                },
            },
            page_index: 1, //页
            page_size: 10, //每页条数
            isLoading: false, //加载
            refreshing: false,
            footer: 0, //上拉底部显示
        };
        this.TabClick = this.TabClick.bind(this);
    }
    TabClick(tab) {
        let temp = this.state.queryCondidate;
        temp.condidate.state = tab.value === 0 ? 0 : tab.value;
        temp.page_index = index;
        temp.page_size = size;
        this.setState(
            {
                queryCondidate: temp,
                tabinfo: tab,
                page_index: index, //页
                page_size: size, //每页条数
            },
            () => {
                this.GetList();
            },
        );
    }
    GetList() {
        getBankApplyList(this.state.queryCondidate).then((r) => {
            if (r.code === 0) {
                console.log(r.data.list);
                this.setState({
                    list: r.data.list,
                    footer: 0,
                });
                if (this.state.page_index === 1) {
                    pagecount = r.data.total_page_count;
                    this.setState({
                        footer: r.data.total_item_count < 10 ? 2 : 0,
                    });
                }
            } else {
                Alert.alert(r.msg);
            }
        });
    }
    AuditOrder(ParkingOrderID, state) {
        Modal.alert('提示', '确认' + (state === 1 ? '通过' : '不通过') + '该订单？', [
            {
                text: '取消',
            },
            {
                text: state === 1 ? '通过' : '不通过',
                onPress: () => {
                    setApplyState({
                        id: ParkingOrderID,
                        state: state,
                    }).then((r) => {
                        if (r.code === 0) {
                            this.GetList();
                        } else {
                            Toast.info(r.msg);
                        }
                    });
                },
            },
        ]);
    }
    FaceOrder(ParkingOrderID) {
        Modal.alert('提示', '确认面签通过该订单？', [
            {
                text: '取消',
            },
            {
                text: '通过',
                onPress: () => {
                    setContractState({
                        id: ParkingOrderID,
                    }).then((r) => {
                        if (r.code === 0) {
                            this.GetList();
                        } else {
                            Toast.info(r.msg);
                        }
                    });
                },
            },
        ]);
    }
    LendingOrder(ParkingOrderID) {
        Modal.alert('提示', '确认放款成功？', [
            {
                text: '取消',
            },
            {
                text: '确认',
                onPress: () => {
                    setBankPayState({
                        id: ParkingOrderID,
                    }).then((r) => {
                        if (r.code === 0) {
                            this.GetList();
                        } else {
                            Toast.info(r.msg);
                        }
                    });
                },
            },
        ]);
    }
    _onRefresh() {
        let temp = this.state.queryCondidate;
        temp.condidate.state = this.state.tabinfo.value;
        temp.page_index = index;
        temp.page_size = size;
        this.setState({footer: 0, page_index: index, page_size: size, queryCondidate: temp}, () => {
            this.GetList();
        });
    }

    //上拉加载更多
    loadData = () => {
        this.setState({isLoading: false});
        let dataArray = [];
        if (pagecount - 1 > 0) {
            pagecount = pagecount - 1;
            this.setState(
                {
                    page_index: this.state.page_index + 1,
                    footer: 1,
                },
                () => {
                    let temp = this.state.queryCondidate;
                    temp.condidate.state = this.state.tabinfo.value;
                    temp.page_index = this.state.page_index;
                    temp.page_size = this.state.page_size;
                    this.setState(
                        {
                            queryCondidate: temp,
                        },
                        () => {
                            getBankApplyList(this.state.queryCondidate).then((r) => {
                                if (r.code === 0) {
                                    dataArray = r.data.list;
                                    dataArray = this.state.list.concat(dataArray);
                                    this.setState({
                                        list: dataArray,
                                        isLoading: false,
                                    });
                                }
                            });
                        },
                    );
                },
            );
        } else {
            this.setState({
                footer: 2,
            });
        }
    };

    //上拉底部显示
    genIndicator() {
        if (this.state.footer === 1) {
            return (
                <View style={styles.indicatorContainer}>
                    <ActivityIndicator style={styles.indicator} size={'large'} animating={true} />
                    <Text style={{textAlign: 'center'}}>正在加载更多</Text>
                </View>
            );
        } else if (this.state.footer === 2) {
            return (
                <View
                    style={{
                        height: 30,
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                    }}>
                    <Text
                        style={{
                            color: '#999999',
                            fontSize: 14,
                            marginTop: 5,
                            marginBottom: 5,
                        }}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if (this.state.footer === 0) {
            return (
                <View
                    style={{
                        height: 30,
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                    }}>
                    <Text
                        style={{
                            color: '#999999',
                            fontSize: 14,
                            marginTop: 5,
                            marginBottom: 5,
                        }}>
                        上拉加载更多
                    </Text>
                </View>
            );
        }
    }
    _renderItem(item) {
        return (
            <WingBlank size="lg">
                <Flex
                    onPress={() => {
                        this.props.navigation.push('MyLoanDetails', {
                            BankApplyID: item.BankApplyID,
                            identity: this.props.userinfo.identity,
                            params: item.ParkingDataID,
                            orderid: item.ParkingOrderID,
                        });
                    }}
                    direction={'row'}
                    style={{
                        padding: 5,
                        flex: 1,
                        backgroundColor: 'white',
                        marginTop: 10,
                        borderRadius: 5,
                    }}>
                    <Flex style={{width: '30%', padding: 10}} direction="column">
                        <Text style={{fontSize: 16, color: '#EC4F46'}}>￥{item.LoanPrice}</Text>
                        <Text style={{fontSize: 12}}>贷款金额</Text>
                    </Flex>
                    <View style={{width: 1, height: 50, backgroundColor: '#EDEDED'}} />
                    <View style={{width: '70%', alignItems: 'flex-start', marginLeft: 21}}>
                        <Text style={{fontSize: 16, fontWeight: 'bold'}}>{item.BuildingName}</Text>
                        <Text style={{fontSize: 16, color: '#999999', marginTop: 8}}>车位号：{item.ParkingName}</Text>
                        {item.ApplyState === 7 ? (
                            <Text style={{fontSize: 14, color: '#999999'}}>
                                贷款进度：<Text style={{color: 'red'}}>审核失败</Text>
                            </Text>
                        ) : item.ApplyState === 4 ? (
                            <Text style={{fontSize: 14, color: '#999999'}}>
                                贷款进度：<Text style={{color: 'red'}}>取消</Text>
                            </Text>
                        ) :(
                            <Text style={{fontSize: 14, color: '#999999'}}>
                                贷款进度:
                                {item.PayState == 0 ? (
                                    <Text style={{color: '#1CA2FF'}}>银行审核中</Text>
                                ) : (
                                    <Text style={{color: '#4ED9A5'}}>放款成功</Text>
                                )}
                            </Text>
                        )}
                    </View>
                    {/* <Flex style={{width: '100%', padding: 10}} justify={'between'}>
                    <Text style={{fontSize: 16, fontWeight: 'bold'}}>贷款人：{item.OwnerName}</Text>
                    <Text style={{fontSize: 14, color: '#999999'}}>电话：{item.Mobile}</Text>
                </Flex>
                <Flex style={{width: '100%', padding: 10}}>
                    <Text style={{fontSize: 16, fontWeight: 'bold'}}>
                        {item.BuildingName}
                        {item.ParkingName}
                    </Text>
                </Flex>
                <Flex style={{width: '100%', padding: 10}} justify={'between'}>
                    <Text style={{fontSize: 16}}>
                        贷款金额:<Text style={{fontSize: 20, color: '#EC4F46'}}>{item.LoanPrice}</Text>元
                    </Text>
                    <Text style={{fontSize: 14, color: '#999999'}}>时间：{item.RegDateTime}</Text>
                </Flex>
                <Flex style={{width: '100%', padding: 10}} justify={'between'}>
                    <Text style={{fontSize: 14, color: '#999999'}}>
                        申请状态:
                        {item.ApplyState == 1
                            ? '正常'
                            : item.ApplyState == 5
                            ? '作废'
                            : item.ApplyState == 6
                            ? '待审'
                            : item.ApplyState == 7
                            ? '审核失败'
                            : '4取消'}
                    </Text>
                    <Text style={{fontSize: 14, color: '#999999'}}>放款状态:{item.PayState == 0 ? '未放' : '已放'}</Text>
                </Flex>
                <Flex style={{width: '100%', paddingRight: 10}} justify={'end'}>
                    {this.props.userinfo.identity === 21 &&
                        item.OrderState === 1 &&
                        item.OrderPayID > 0 &&
                        item.DepositState === 1 &&
                        item.OrderContractState === 1 &&
                        item.ApplyState === 6 &&
                        item.ContractState === 0 && (
                            <>
                                <Text
                                    onPress={() => {
                                        this.AuditOrder(item.BankApplyID, 1);
                                    }}
                                    style={{backgroundColor: 'red', padding: 5, color: 'white', borderRadius: 5}}>
                                    {' '}
                                    通过
                                </Text>
                                <Text
                                    onPress={() => {
                                        this.AuditOrder(item.BankApplyID, 7);
                                    }}
                                    style={{backgroundColor: 'red', padding: 5, color: 'white', borderRadius: 5}}>
                                    不通过
                                </Text>
                            </>
                        )}
                    {this.props.userinfo.identity === 21 &&
                        item.OrderState === 1 &&
                        item.OrderPayID > 0 &&
                        item.DepositState === 1 &&
                        item.OrderContractState === 1 &&
                        item.ApplyState === 1 &&
                        item.ContractState === 0 && (
                            <Text
                                onPress={() => {
                                    this.FaceOrder(item.BankApplyID);
                                }}
                                style={{backgroundColor: 'red', padding: 5, color: 'white', borderRadius: 5}}>
                                面签通过
                            </Text>
                        )}
                    {this.props.userinfo.identity === 21 && item.ApplyState === 1 && item.PayState === 0 && item.ContractState === 1 && (
                        <Text
                            onPress={() => {
                                this.LendingOrder(item.BankApplyID);
                            }}
                            style={{backgroundColor: 'red', padding: 5, color: 'white', borderRadius: 5}}>
                            贷款发放
                        </Text>
                    )}
                    <Text
                        onPress={() => {
                            this.props.navigation.push('PayLoan', {
                                params: item.ParkingDataID,
                                orderid: item.ParkingOrderID,
                            });
                        }}
                        style={{backgroundColor: 'red', padding: 5, color: 'white', borderRadius: 5}}>
                        查看详情
                    </Text>
                </Flex> */}
                </Flex>
            </WingBlank>
        );
    }
    render() {
        return (
            <View style={{flex: 1}}>
                <Tabs tabs={this.state.tabs} prerenderingSiblingsNumber={0} initialPage={this.state.index} onChange={this.TabClick}>
                    <FlatList
                        data={this.state.list}
                        style={{width: '100%'}}
                        showsVerticalScrollIndicator={false}
                        renderItem={(data) => this._renderItem(data.item, index)}
                        keyExtractor={(item, index) => index}
                        // ListHeaderComponent={this._HeaderView}
                        ListFooterComponent={() => this.genIndicator()} //上拉加载更多视图
                        onEndReached={() => {
                            this.loadData();
                        }}
                        onEndReachedThreshold={0.1} // 这个属性的意思是 当滑动到距离列表内容底部不足 0.1*列表内容高度时触发onEndReached函数 为啥要加这个属性 因为不加的话滑动一点点就会立即触发onReached函数，看不到菊花加载中
                        refreshing={true}
                        refreshControl={
                            <RefreshControl
                                refreshing={this.state.refreshing}
                                onRefresh={() => {
                                    this._onRefresh();
                                }}
                            />
                        }
                    />
                </Tabs>
            </View>
        );
    }
}

export default connect(mapGetter)(myLoan);
export const title = 'Tabs';
export const description = 'Tabs example';
const styles = StyleSheet.create({});
